#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void *read_file(char *file_name, unsigned long *length)
{
	FILE *file;
	file = fopen(file_name, "r");
	if(!file) {
		printf("Failed to open file: %s\n", file_name);
		exit(1);
	}
	int error = fseek(file, 0, SEEK_END);
	if(error == -1) {
		printf("Failed to SEEK_END: %s\n", file_name);
		exit(1);
	}
	long len = ftell(file);
	if(len == -1) {
		printf("Failed to ftell: %s\n", file_name);
		exit(1);
	}
	rewind(file);
	void *data = malloc(len);
	size_t result;
	result = fread(data, 1, len, file);
	if(result != len) {
		printf("Failed to read all bytes: %s\n", file_name);
		exit(1);
	}
	fclose(file);
	printf("read_file: File length %u\n", len);
	*length = len;
	return data;
}

int main(int argnr, char *args[])
{
	if(argnr <= 2) {
		printf("Please provide output / input file\n");
		exit(1);
	}
	char *input_file = args[2];
	char *output_file = args[1];
	unsigned long len;
	unsigned char *file_data = read_file(input_file, &len);
	unsigned long i;
	FILE *f = fopen(output_file, "w");
	if(!f) {
		printf("Failed to open output file\n");
		exit(1);
	}
	fprintf(f, "/* Header generated by bin2c from binary file %s */\n\n\n", input_file);
	fprintf(f, "#define BIN_LENGTH %u\n", len);
	fprintf(f, "unsigned char bin[] = {");
	for(i = 0; i < (len - 1); i++) {
		if(i % 10 == 0)
			fprintf(f, "\n\t");
		fprintf(f, "0x%02x, ", file_data[i]);
	}
	fprintf(f, "0x%02x\n};\n", file_data[i]);
	fclose(f);
	return 0;
}
